﻿#include "global_manager.h"
#include "easylogging++.h"

const QString SQLITE_DB_PATH         = "data/effective_life.db";
const QString SQLITE_DB_CONNECT_NAME = "effective_life";
const QString PRJ_INFO_TABLE_NAME    = "prj_info";
const QString TASK_INFO_TABLE_NAME   = "task_info";
const QString PLAN_INFO_TABLE_NAME   = "plan_info";

GlobalManager* GlobalManager::m_instance = nullptr;
QHash<QString, QVector<int> > GlobalManager::m_investmentTimeMap;


GlobalManager *globalManager = GlobalManager::getInstance();


GlobalManager* GlobalManager::getInstance()
{
    if (m_instance == nullptr)
    {
        m_instance = new GlobalManager();
    }

    return m_instance;
}

void GlobalManager::setTaskInvestmentTime(QString uuid, QVector<int> investmentTime)
{
    m_investmentTimeMap[uuid] = investmentTime;
}

QHash<QString, QVector<int> > GlobalManager::getTaskInvestmentTime()
{
    return m_investmentTimeMap;
}

QString GlobalManager::formatHHMMSSFromSecond(int seconds)
{
    int second = seconds % 60;
    int minutes = seconds / 60;
    int minute = minutes % 60;
    int hour = minutes / 60;
    return QString("%1:%2:%3").arg(hour, 2, 10, QChar('0'))
                              .arg(minute, 2, 10, QChar('0'))
        .arg(second, 2, 10, QChar('0'));
}

GlobalManager::GlobalManager() :
    QObject(nullptr),
    m_timer(nullptr),
    m_sqlOperator(new SqliteManager)
{

}

void GlobalManager::initTimer()
{
    if (nullptr != m_timer)
    {
        return ;
    }

    m_timer = new QTimer(this);
    m_timer->setInterval(1000);

    connect(m_timer, &QTimer::timeout, this, &GlobalManager::saveInvestmentTime);

    m_timer->start();
}

void GlobalManager::saveInvestmentTime()
{
    QHash<QString, QVector<int> > investmentTime = m_investmentTimeMap;
    m_investmentTimeMap.clear();

    for (auto it = investmentTime.begin(); it != investmentTime.end(); ++it) {
        QHash<QString, QVariant> data;
        data["today_investment_time"] = it.value()[0];
        data["total_investment_time"] = it.value()[1];

        QHash<QString, QVariant> whereCondition;
        whereCondition["uuid"] = it.key();
        bool ret = m_sqlOperator->updateData("task_info", data, whereCondition);
        if (!ret)
        {
            LOG(ERROR) << "update data failed, error info: " << m_sqlOperator->lastError().toStdString();
        }
    }

}
